import type { ObjectDirective } from "vue";

const DISTANCE = 50;
const DURATION = 1000;
const animationMap = new WeakMap();
const ob = new IntersectionObserver((entries) => {
	for (const entry of entries) {
		if (entry.isIntersecting) {
			const animation = animationMap.get(entry.target);
			animation.play();
			ob.unobserve(entry.target);
		}
	}
});

/**
 * @description 判断视窗
 */
function isBelowViewporr(el: HTMLElement) {
	const rect = el.getBoundingClientRect();
	return rect.top > window.innerHeight;
}
const slideIn: ObjectDirective = {
	mounted(el: HTMLElement) {
		if (!isBelowViewporr(el)) return;

		const animation = el.animate(
			[
				{
					transform: `translateY(${DISTANCE}px)`,
					opacity: 0.5,
				},
				{
					transform: `translateY(${0}px)`,
					opacity: 1,
				},
			],
			{
				duration: DURATION,
				easing: "ease",
			},
		);
		animation.pause();
		animationMap.set(el, animation);
		ob.observe(el);
	},
	unmounted(el: HTMLElement) {
		ob.unobserve(el);
	},
};

export default { name: "slide-in", ...slideIn };
